<!--
 * @Author: linZeJian
 * @Date: 2022-08-24 10:53:55
 * @LastEditors: linZeJian
 * @LastEditTime: 2022-11-10 11:09:01
 * @Description: 
-->
<template>
  <div v-if="option.display">
    <uni-forms-item
      :label="option.label"
      :required="option.required"
      :rules="[{ required: option.required, errorMessage: '必填项不能为空' }]"
      :name="option.prop"
    >
      <div v-if="!detailValue" style="color: #ef9797; padding-left: 10px">
        <!-- 自定义添加按钮 -->
        <div
          style="
            color: #fff;
            background-color: #1aad19;
            border: 1px solid #1aad19;
            border-radius: 4px;
            font-size: 12px;
            padding: 4px 12px;
            width: 50px;
            text-align: center;
            float: left;
          "
          @click.stop="addColumn"
        >
          添加
        </div>
      </div>
    </uni-forms-item>

    <!-- 已填加子表单项 -->
    <div
      style="
        margin-top: -18px;
        margin-left: -10px;
        margin-bottom: 10px;
        border-bottom: 1px solid #d4d4d4;
      "
    >
      <div v-if="childrenColumnCopy.columnObjArr.length > 0">
        <div
          v-for="(item, index) in childrenColumnCopy.columnObjArr"
          :key="index"
          class="item"
        >
          <div class="item-com">
            <div style="line-height: 30px" @click="handleItemFunc(item, index)">
              {{ item[0].label }}:{{
                itemForm[index][item[0].prop] || "点击完善"
              }}
            </div>
            <uni-icons
              v-if="!detailValue"
              type="trash"
              size="20"
              @click="deleteColumn(index)"
            ></uni-icons>
          </div>
        </div>
      </div>
      <div
        v-else
        style="
          font-size: 14px;
          background: #ffffff;
          color: #a4a4a4;
          padding: 6px 20px;
          text-align: left;
        "
      >
        暂无相关数据
      </div>
    </div>

    <!-- 子表单弹窗填写 -->
    <uni-popup
      ref="alertDialog"
      mode="bottom"
      @close="handleBeforeClose"
      @maskClick=""
      :style="{ 'max-height': '70%' }"
      background-color="#fff"
    >
      <div style="padding: 20px 14px; max-height: 70vh; overflow-y: auto">
        <uni-forms
          ref="valiFormDynamic"
          :key="updateShow"
          :modelValue="handleItemForm"
          label-position="top"
          label-width="auto"
        >
          <!-- <component
            :is="getTypeExchange(column.type)"
            v-model="handleItemForm[column.prop]"
            v-for="column in handleItem.column"
            :key="column.prop"
            :option="column"
          ></component> -->
          <template v-if="handleItem.column">
            <!-- {{ JSON.stringify(handleItemForm) }} -->
            <!-- 子表单小程序数据又不更新了，数据子表单形式的数据嵌套不能数据绑定 -->
            <!-- 弹框子组件 不是页面 故没有自己的 onLoad 和 onShow 方法， -->
            <!-- 同时ta自己的 created 方法在已进入到父级页面时候就已经触发了 -->
            <!-- <forms-item
              ref="formItemTest"
              :option="handleItem"
              :forms="handleItemForm"
              @change="change"
            >
            </forms-item> -->

            <!-- 只能但单组件适配 -->
            <view v-for="(item, index) in handleItem.column" :key="item.prop">
              <template
                v-if="
                  item.type == 'input' ||
                  item.type == 'password' ||
                  item.type == 'textarea'
                "
              >
                <!-- // a-uni-input组件测试与实现,结果配置auni-input即可，其它都会响应了？？？bug,还是得一个一个配置 -->
                <auni-input
                  :option="item"
                  v-model="handleItemForm"
                  @change="change"
                ></auni-input>
                <!-- {{handleItemForm[item.prop]}}{{item.prop}}{{handleItemForm}} -->
              </template>
              <template v-else-if="item.type == 'number'">
                <auni-number
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-number>
              </template>
              <template v-else-if="item.type == 'map'">
                <auni-city-picker
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-city-picker>
              </template>
              <template v-else-if="item.type == 'radio'">
                <auni-radio
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-radio>
              </template>
              <template v-else-if="item.type == 'checkbox'">
                <auni-checkbox
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-checkbox>
              </template>
              <template v-else-if="item.type == 'select'">
                <auni-select
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-select>
              </template>
              <template v-else-if="item.type == 'cascader'">
                <auni-cascader
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-cascader>
              </template>
              <template v-else-if="item.type == 'date'">
                <auni-date
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-date>
              </template>
              <template v-else-if="item.type == 'datetime'">
                <auni-datetime
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-datetime>
              </template>
              <template v-else-if="item.type == 'time'">
                <auni-time
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-time>
              </template>
              <template v-else-if="item.type == 'switch'">
                <auni-switch
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-switch>
              </template>
              <template v-else-if="item.type == 'rate'">
                <auni-rate
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-rate>
              </template>
              <template v-else-if="item.type == 'slider'">
                <auni-slider
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-slider>
              </template>
              <template v-else-if="item.type == 'upload'">
                <auni-upload
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-upload>
              </template>
              <template v-else-if="item.type == 'customUpload'">
                <auni-upload-custom
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-upload-custom>
              </template>
              <template v-else-if="item.type == 'customInfo'">
                <auni-info-custom
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-info-custom>
              </template>
              <template v-else-if="item.type == 'dynamic'">
                <div style="color: #ef9797">子表单内不能嵌套子表单</div>
              </template>
              <template v-else-if="item.type == 'customCrud'">
                <div style="color: #ef9797">子表单内不能嵌套crud</div>
              </template>
              <template v-else-if="item.type == 'customGroup'">
                <auni-group-custom
                  :option="item"
                  :value="handleItemForm"
                ></auni-group-custom>
              </template>
              <template v-else>
                <auni-undefined
                  :option="item"
                  v-model="handleItemForm[item.prop]"
                ></auni-undefined>
              </template>
            </view>
          </template>
          <template v-else>
            <view
              style="
                font-size: 14px;
                background: #ffffff;
                color: #a4a4a4;
                padding: 6px 20px;
                text-align: center;
              "
              >暂无相关数据</view
            >
          </template>
          <div style="margin: 30px 16px 10px">
            <button
              v-if="!detailValue"
              type="primary"
              @click="submit('valiFormDynamic')"
              class="ptb16 mt60 mb20"
            >
              确定
            </button>
          </div>
        </uni-forms>
      </div>
    </uni-popup>
  </div>
</template>

<script>
// 注意：通过pages.json的easycom实现自动注册的组件内，使用import formsItem from "../formsItem.vue";组件单独引入无效！！
// import formsItem from "../formsItem.vue";
export default {
  name: "auni-dynamic",
  components: {
    // formsItem,
  },
  props: {
    option: Object,
    value: [String, Number, Array, Object],
  },
  data() {
    return {
      show: false,
      updateShow: false,

      childrenOrigin: {
        align: "center",
        column: [],
        emptyBtn: true,
        emptyText: "清空",
        gutter: 0,
        labelPosition: "left",
        labelSuffix: "：",
        labelWidth: 120,
        menuBtn: true,
        menuPosition: "center",
        submitBtn: true,
        submitText: "确定",
      },
      childrenOriginColumn: [],
      childrenOriginColumnLen: null,
      childrenColumnCopy: {
        align: "center",
        // 单项
        column: [],
        // 对象--展示使用
        columnObjArr: [],
        menuBtn: false,
      },

      handleItem: {
        align: "center",
        column: [],
        emptyBtn: false,
        emptyText: "清空",
        gutter: 0,
        labelPosition: "left",
        labelSuffix: "：",
        labelWidth: 120,
        menuBtn: true,
        menuPosition: "center",
        submitBtn: true,
        submitText: "确定",
      },

      // 子表单填写数据
      itemForm: this.value[this.option.prop] || [],
      handleItemForm: {},
      handleItemFormIndex: null,

      comValue: this.value[this.option.prop] || [],
    };
  },
  computed: {
    // comValue: {
    //   get() {
    //     console.log("this.option :>> ", this.option);
    //     //console.log("this.value111 :>> ", this.value);
    //     // 解决van-field的value绑定数据类型问题
    //     // 但是改变了van-form返回值
    //     // van-field 的:value="comValue"数据类型校验报错不管，不然回改变值的绑定
    //     // if (this.value == "" || this.value == undefined) {
    //     //   let valueArray = "";
    //     //   return valueArray;
    //     // }
    //     // if (
    //     //   Object.prototype.toString
    //     //     .call(this.value)
    //     //     .slice(8, -1)
    //     //     .toLowerCase() == "array"
    //     // ) {
    //     //   if (this.value.length == 0) {
    //     //     return 1;
    //     //   } else {
    //     //     return 0;
    //     //   }
    //     // }
    //     return this.value;
    //   },
    //   set(val) {
    //     // 触发value绑定值的交互与更新
    //     this.$emit("input", val);
    //     // this.$emit("value:update",val)
    //   },
    // },
    // 处理详情模式
    detailValue() {
      if (this.option.detail) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {},
  watch: {
    // 这个不能省
    itemForm: {
      deep: true,
      immediate: true,
      handler(newV) {
        // console.log("dynamic itemForm", newV);
        this.$emit("input", newV);
        // this.value[this.option.prop] = newV;
        // this.$emit("change",newV,this.option.prop)
      },
    },
    value: {
      deep: true,
      immediate: true,
      handler(newV) {
        // console.log('newV222222', newV)
      },
    },

    handleItemForm: {
      deep: true,
      immediate: true,
      handler(newV) {
        // console.log("dynamic handleItemForm", newV);
        // this.$emit("change",newV,this.option.prop)
      },
    },
    comValue: {
      deep: true,
      immediate: true,
      handler(newV) {
        // console.log("dynamic comValue :>> ", newV);
        // 触发value绑定值的交互与更新
        this.$emit("input", newV);
        // this.value[this.option.prop] = newV;
        // this.$emit("change",newV,this.option.prop)
      },
    },
  },
  mounted() {
    // console.log("this.option", this.option);
    // 初始化，处理普通表单的column
    let columuCopy = this.option.children.column;
    // 同AvueFormMobile组件移动端转换表单项
    // if (columuCopy && columuCopy.length > 0) {
    //   columuCopy.forEach((item) => {
    //     item = this.handleMobileOption(item);
    //   });
    // }
    this.childrenOrigin.column = columuCopy;
    this.childrenOriginColumn = columuCopy;
    this.childrenOriginColumnLen = columuCopy.length || 0;
    // console.log("this.childrenOrigin :>> ", this.childrenOrigin);

    // 数据回显
    if (
      Object.prototype.toString
        .call(this.itemForm)
        .slice(8, -1)
        .toLowerCase() == "array"
    ) {
      let columnObj = [...columuCopy];
      // console.log("this.itemForm", this.itemForm);
      // 数据回显显示结构
      this.itemForm.forEach((item, index) => {
        this.childrenColumnCopy.columnObjArr.push(columnObj);
      });
    }
  },
  methods: {
    change(dynamic, prop) {
      // console.log("dynamic ,prop:>> ", dynamic,prop);
      let obj = {};
      obj[prop] = dynamic;
      // console.log('this.handleItemForm :>> ', this.handleItemForm);
      this.handleItemForm = Object.assign(this.handleItemForm, obj);
      // console.log('this.handleItemForm2222 :>> ', this.handleItemForm);
      this.$forceUpdate();
    },
    /**
     * @description: 添加子项
     * @return {*}
     */
    addColumn() {
      // console.log("this.comValue", this.comValue);
      // this.childrenColumnCopy.column.push(...this.childrenOrigin.column);
      // 这里的es6对象解构低版本企业微信不能用
      // this.childrenColumnCopy.columnObjArr.push({
      //   ...this.childrenOrigin.column,
      // });
      this.handleBeforeClose();
      let columnObj = [];
      this.childrenOrigin.column.forEach((item, index) => {
        columnObj.push(item);
      });
      this.childrenColumnCopy.columnObjArr.push(columnObj);

      // 初始生成数据
      let dataPropOrigin = {};
      this.childrenOrigin.column.forEach((item) => {
        // 子表单嵌套子表单数据
        if (item.type == "dynamic") {
          dataPropOrigin[item.prop] = [];
        } else {
          dataPropOrigin[item.prop] = "";
        }
      });
      this.itemForm.push(dataPropOrigin);
      this.updateShow = false;
      this.$nextTick(() => {
        this.updateShow = true;
      });
      // console.log("this.itemForm", this.itemForm);
    },
    /**
     * @description: 删除子项
     * @return {*}
     */
    deleteColumn(index) {
      console.log("index", index);
      this.childrenColumnCopy.columnObjArr.splice(index, 1);
      this.itemForm.splice(index, 1);
    },
    /**
     * @description: 点击子项打开抽屉
     * @param {*} itemObj
     * @return {*}
     */
    handleItemFunc(itemObj, index) {
      this.handleBeforeClose();
      this.handleItem.column = [];
      // console.log("itemObj", itemObj);
      for (var i in itemObj) {
        this.handleItem.column.push(itemObj[i]);
      }
      //console.log('this.itemForm :>> ', this.itemForm);
      this.handleItemForm = this.itemForm[index]; //不生效
      this.setData({ handleItemForm: this.itemForm[index] });
      this.$nextTick(() => {
        this.handleItemForm = this.itemForm[index]; //不生效
        this.setData({ handleItemForm: this.itemForm[index] });
        this.$forceUpdate();
      });
      this.handleItemFormIndex = index;
      this.show = true;
      this.$refs.alertDialog.open("bottom");
      // this.$refs.formItemTest.first();
      this.updateShow = false;
      this.$nextTick(() => {
        this.updateShow = true;
      });
      this.$forceUpdate();
      console.log("this.handleItemForm :>> ", this.handleItemForm);
    },

    // 子表单项预览 - 弹窗 - 关闭前
    handleBeforeClose() {
      // this.$refs.valiFormDynamic.resetFields();//1.4.0 已弃用
      this.handleItem.column = [];
      this.handleItemFormIndex = null;
      this.show = false;
    },

    /**
     * @description: 点击提交 uni-forms 数据返回
     * @param {*} ref
     * @return {*}
     */
    submit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          // uni.showToast({
          //   title: `校验通过`,
          // });
          console.log("uni-forms-dynamic-res", res);
          console.log("this.handleItemForm", this.handleItemForm);
          // 合并数据，解决单组件数据绑定问题
          // let allFinalData = Object.assign(res, this.handleItemForm);
          // console.log("allFinalData", allFinalData);
          // 处理子表单数据
          this.itemForm[this.handleItemFormIndex] = Object.assign(
            this.itemForm[this.handleItemFormIndex],
            res
          );
          this.$emit("change", this.itemForm, this.option.prop);
          this.$refs.alertDialog.close();
        })
        .catch((err) => {
          console.log("err", err);
          uni.showToast({
            title: `校验不通过，请检查表单`,
            icon: "error",
            duration: 2000,
          });
        });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split(".");
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }
          data = data[key2];
        });
      });
    },
  },
};
</script>

<style scoped>
.item {
  background: #ffffff;
  font-size: 14px;
  color: #808080;
}
.item-com {
  display: flex;
  justify-content: space-between;
  padding: 2px 20px;
}
/* // hover 电脑端可行，移动端不行 */
.item-com .item-hover {
  display: none;
}
.item-com:hover .item-hover {
  display: block;
}
</style>
